<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/29 0029
 * Time: 14:39
 */

namespace app\admin\controller\money;

use app\admin\BaseController;
use app\admin\model\Money as MoneyService ;
use app\admin\model\MoneyRecord;
use app\admin\model\User;
use app\admin\model\Config;
use app\common\controller\alipayController;
use app\lib\exception\FailedException;
use app\Validate\PageMustValidate;
use think\Db;
use think\Request;

class Money extends BaseController
{
    /**
     * [初次全局]给所有没有钱包的用户新建钱包
     * @return \think\response\Json
     * @throws FailedException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function insertUserMoney(){
        $userService = new User();
        $MoneyService = new MoneyService();

        /**
         * SQL select * from om_user
        LEFT JOIN om_money on om_user.id = om_money.user_id
        where money is null
         */
        //查询所有没有钱包的用户
        $list = $userService
            ->field("om_user.*")
            ->join("om_money","om_user.id = om_money.user_id","left")
            ->where("money is null")->select()->toArray();

        //钱包初始化
        $data["money"] = 0;
        $data["credits"] = 0;
        foreach ($list as $k => $v){
            $data["user_id"] = $v["id"];
            if($MoneyService->insert($data) > 0){
                continue;
            }else{
                throw new FailedException(['msg' => $v["id"]."添加失败:"]);
            }
        }
        return writeJson("200","添加成功");
    }

    /**
     * 查询钱包模块设置
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMoneyConfigInfo(){
        $configService = new Config();
        $list = $configService->where("id in (11,12,13,14,15,16)")->select();
        $data = [];
        foreach ($list as $k => $v){
            if($v["id"] == 11){ $data["isOpen"]=$v["v"];}
            if($v["id"] == 12){ $data["invite_rule"]=$v["v"];}
            if($v["id"] == 13){ $data["out_rule"]=$v["v"];}
            if($v["id"] == 14){ $data["invite_img"]=$v["v"];}
            if($v["id"] == 15){ $data["down_ad_img"]=$v["v"];}
            if($v["id"] == 16){ $data["down_ios_img"]=$v["v"];}
        }
        return writeJson("200",$data);
    }

    /**
     * 设置钱包开启关闭 [0关闭 1开启]
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     */
    public function updateConfigIsOpen(Request $request){
        $configService = new Config();
        $post = $request->post();
        if(!isset($post["isOpen"]) || ($post["isOpen"] != "0" && $post["isOpen"] != "1")){
            throw new FailedException(['msg' => "输入值有误，请重新输入"]);
        }
        $where["k"] = "money_is_open";
        if($configService->fieldUpdate('v',$post["isOpen"],'',$where)){
            return writeJson("200","更新成功");
        }else{
            throw new FailedException(['msg' => "更新失败"]);
        }
    }

    /**
     * 设置钱包分销规则说明
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     */
    public function updateConfigInviteRule(Request $request){
        $configService = new Config();
        $post = $request->post();
        if(!isset($post["inviteRule"])){
            throw new FailedException(['msg' => "参数有误，请重新输入"]);
        }
        $where["k"] = "money_invite_rule";
        if($configService->fieldUpdate('v',$post["inviteRule"],'',$where)){
            return writeJson("200","更新成功");
        }else{
            throw new FailedException(['msg' => "更新失败"]);
        }
    }

    /**
     * 设置钱包提现规则说明
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     */
    public function updateConfigOutRule(Request $request){
        $configService = new Config();
        $post = $request->post();
        if(!isset($post["outRule"])){
            throw new FailedException(['msg' => "参数有误，请重新输入"]);
        }
        $where["k"] = "money_out_rule";
        if($configService->fieldUpdate('v',$post["outRule"],'',$where)){
            return writeJson("200","更新成功");
        }else{
            throw new FailedException(['msg' => "更新失败"]);
        }
    }

    /**
     * 设置钱包邀请页封面图
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     */
    public function updateConfigInviteImg(Request $request){
        $configService = new Config();
        $post = $request->post();
        if(!isset($post["inviteImg"])){
            throw new FailedException(['msg' => "参数有误，请重新输入"]);
        }
        $where["k"] = "money_invite_img";
        if($configService->fieldUpdate('v',$post["inviteImg"],'',$where)){
            return writeJson("200","更新成功");
        }else{
            throw new FailedException(['msg' => "更新失败"]);
        }
    }

    /**
     * 设置安卓下载二维码
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     */
    public function updateConfigDownAdImg(Request $request){
        $configService = new Config();
        $post = $request->post();
        if(!isset($post["adImg"])){
            throw new FailedException(['msg' => "参数有误，请重新输入"]);
        }
        $where["k"] = "down_ad_img";
        if($configService->fieldUpdate('v',$post["adImg"],'',$where)){
            return writeJson("200","更新成功");
        }else{
            throw new FailedException(['msg' => "更新失败"]);
        }
    }

    /**
     * 设置IOS下载二维码
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     */
    public function updateConfigDownIosImg(Request $request){
        $configService = new Config();
        $post = $request->post();
        if(!isset($post["iosImg"])){
            throw new FailedException(['msg' => "参数有误，请重新输入"]);
        }
        $where["k"] = "down_ios_img";
        if($configService->fieldUpdate('v',$post["iosImg"],'',$where)){
            return writeJson("200","更新成功");
        }else{
            throw new FailedException(['msg' => "更新失败"]);
        }
    }

    /**
     * 查询提现审核列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     * @throws \think\exception\DbException
     */
    public function getMoneyAuditList(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $recordService = new MoneyRecord();
        $where["money_source_type"] = 1;  //账单来源(0拥金 1提现)
        $where["money_type"] = 1;         //金额类型 1 支出

        $dataList = $recordService
            ->field("om_money_record.id,om_user.nickname,om_user.phone,om_user.head_img,money,audit_status,om_money_record.create_time,audit_time_remark,pay_type,pay_status")
            ->join("om_user","om_money_record.user_id = om_user.id")
            ->where($where)
            ->order("om_money_record.id desc")
            ->paginate($post['page_number'], false, ['page' => $post['page']]);

        foreach ($dataList as $k=>$v){
            $v["audit_status_str"] = $recordService->getAuditStatusStr($v["audit_status"]);
            $v["pay_type_str"] = $recordService->getPayTypeStr($v["pay_type"]);
            $v["pay_status_str"] = $recordService->getPayStatusStr($v["pay_status"]);
        }
        return writeJson('200',$dataList);
    }

    /**
     * 查询钱包明细-根据用户ID
     * @param $user_id
     * @return array|null|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMoney($user_id){
        $MoneyService = new MoneyService();
        $where["user_id"] = $user_id;
        return $MoneyService->where($where)->find();
    }

    /**
     * 提现发起
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userPayOut(Request $request){
        $post = $request->post();
        if(!isset($post["id"])){ return writeJson(200,"请传入ID","请传入ID",10000); }
        //获取账单id
        $recordService = new MoneyRecord();
        $where["id"] = $post["id"];
        $model = $recordService->where($where)->find();
        if($model == null){ return writeJson(200,"当前账单不存在","当前账单不存在",10000); }
        if($model["audit_status"] != 1){ return writeJson(200,"审核未通过","审核未通过",10000); }
        if($model["pay_type"] == 0){ return writeJson(200,"当前暂不支持微信提现","当前暂不支持微信提现",10000); }

        //发起提现
        $alipay = new alipayController();
        $result = $alipay->payOut($model["order_number"],$model["money"],$model["ali_identity"],$model["ali_name"]);

        if($result["code"] != 200){
//            $update = array("id" =>$post["id"],"pay_status" =>1,"pay_time" =>time());
//            $recordService->update($update);
            return writeJson(200,$result["msg"],$result["msg"],10000);
        }

        //提现成功的话更改账单状态
        $update = array( "id" =>$post["id"],"pay_status" =>2,"pay_time" =>time());
        $res = $recordService->update($update);
        if(!$res){
            return writeJson(200,"状态修改失败","状态修改失败",10000);
        }
        return writeJson(200,"操作成功");
    }

    /**
     * 提现审核
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function setOutAudit(Request $request){
        $post = $request->post();
        if(!isset($post["id"])){ return writeJson(200,"请传入ID","请传入ID",10000); }
        if(!isset($post["audit_status"])) {
            return writeJson(200,"请选择审核状态","请选择审核状态",10000); }
        //获取账单id
        $recordService = new MoneyRecord();
        $moneyService = new \app\admin\model\Money();
        $where["id"] = $post["id"];
        //获取提现信息
        $model = $recordService->where($where)->find();
        if($model["audit_status"] == 2){
            return writeJson(200,"不可二次驳回","不可二次驳回",10000);
        }

        Db::startTrans();
        //若驳回则需要金额原路返回
        if($post["audit_status"] == 2){
            //恢复钱包中的剩余金额
            $res = $moneyService->where(["id"=>$model["money_id"]])->setInc("money",$model["money"]);
            if(!$res){
                Db::rollback();
                return writeJson(200,"金额退回失败","金额退回失败",10000);
            }
        }

        //更改账单信息
        $res = $recordService->fieldUpdate("audit_status",$post["audit_status"],"",$where);
        if(!$res){
            Db::rollback();
            return writeJson(200,"审核失败","审核失败",10000);
        }

        Db::commit();
        return writeJson(200,"操作成功");
    }
}